package world.snowcrystal.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import world.snowcrystal.dao.Article;
import world.snowcrystal.exception.ArticleNotFoundNormalBaseException;
import world.snowcrystal.mapper.ArticleMapper;
import world.snowcrystal.service.ArticleProvideService;

import java.util.List;

@Service
public class DefaultArticleProvideService
        implements ArticleProvideService {

    @Autowired
    private ArticleMapper mapper;

    @Override
    public List<Article> getArticlesByViewCountAsc(int topN) {
        return mapper.selectList(new QueryWrapper<Article>()
                .orderByAsc("view_count")
                .select(Article.class, p -> !p.getColumn().equals("uuid"))
                .last("limit " + topN));
    }

    @Override
    public List<Article> getArticlesByViewCountDesc(int topN) {
        return mapper.selectList(new QueryWrapper<Article>()
                .select(
                        "view_count",
                        "id"
                        , "mime_type"
                        , "last_modification_time"
                        , "thumbnail"
                        , "status",
                        "summary"
                        , "content"
                        , "bin_to_uuid(uuid,1) as uuid"
                        , "content"
                        , "title"
                        ,"category_id"
                        , "author",
                        "create_time")
                .orderByDesc("view_count")
                .last("limit " + topN)
        );
    }

    @Override
    public Article getArticleById(long id) throws ArticleNotFoundNormalBaseException {
        Article article = mapper.selectById(id);
        if (article == null) {
            throw new ArticleNotFoundNormalBaseException(id);
        }
        return article;
    }


}
